<!--suppress ALL -->
<template>
  <div class="page page-message" data-page="message" style="overflow: hidden;">
    <div class="link-tab-page-top">
      <div class="link-tab-page-title" style="float: left;font-weight: bold;">消息</div>
      <span id="message_num" class="btn-clean-unread" @click="message_read">
        清除未读<i class="iconfont icon-APPicon_qingchu"></i>
      </span>
      <a href="#" class="link" @click="message_setup()" style="right: 10px;">
        <i class="iconfont icon-APPicon_shezhi" style="font-size:26px !important;margin-top: -5px;"></i>
      </a>
    </div>
    <!-- <div id="message_num" class="messge-toolTip">
      <i class="iconfont icon-xiaoxi1" style="font-size: 20px;"></i>
      <div id="unreadMessages"></div>
      <div @click="message_read" class="allRead">
        <span class="fl">全部已读</span>
        <i class="iconfont icon-youjiantoushixinxiao" style="font-size: 20px;"></i>
      </div>
    </div> -->
    <div class="notice-bar" id="msgSetTip">
      <div class="notice-bar__text" @click="message_setup">您已关闭部分消息提醒，点击这里重新开启！</div>
      <i class="notice-bar__icon iconfont icon-APPicon_guanbi" @click="handleCloseMsgSetNotice"></i>
    </div>
    <div class="link-page-search">
      <div class="link-page-search-input" style="width: 100%;">
        <i class="iconfont icon-APPicon_sousuo1"></i>
        <input type="text" placeholder="搜一搜" id="unitSearchPopup">
      </div>
    </div>
    <div class="page-content infinite-scroll-content ptr-content" style="padding-bottom: 160px;width: 100%;"
        data-infinite-distance="50" 
        @infinite="getMoreMessageList" 
        @ptr:refresh="refreshMessage">
        <div class="ptr-preloader" id="message_preloader" style="top: -38px;">
          <div class="preloader color-multi"></div>
          <div class="ptr-arrow"></div>
        </div>
        <div>
          <div class="no-hairline-top list search-list media-list searchbar-found" style="margin: 10px 20px;">
            <ul id="contactslist"></ul>
            <div id="msg-preloader" class="preloader infinite-scroll-preloader"></div>
          </div>
        </div>
    </div>
  </div>
</template>

<script>
  return {
    mounted() {
      let self = this;
      self.tabId = 1;
    },
    data: function () {
      return {
        pageIndex: 0,
        allowInfinite_mesage: true,
        pushTimeIsToday: false, //是不是今天
        haveTodayDes: false, //页面上是否显示 以上是今日消息
      }
    },
    methods: {
      handleCloseMsgSetNotice(){
        localStorage.setItem(`${userInfor.accountName}_closeMsgSetTip`,'1')
        $('#msgSetTip').remove()
        $('.page-message').removeClass('show-msgSetNotice')
      },
      backToRefresh:function(){
        /* let self = this;
        self.clearContent();
        self.getList();
        getUnReadMsgCount(); */
      },
      //下拉刷新
      refreshMessage: function (e, done) {
        if (done && e) {
          let self = this;
          let $ = self.$$;
          self.haveTodayDes = false;
          if(1 === e){
            common.loading(1);
          }
          setTimeout(function () {
            self.clearContent();
            self.getList();
            getUnReadMsgCount();
            done();
            if(1 === e){
              common.loading(0);
            }
          }, 1000);
        }
      },
      //滚动分页
      getMoreMessageList: function () {
        let self = this;
        if (!self.allowInfinite_mesage) return;
        self.allowInfinite_mesage = false;
        setTimeout(function () {
          self.pageIndex++;
          self.allowInfinite_mesage = true;
          self.getList();
        }, 500);
      },
      //接收推送消息，过来刷新页面
      receivePushMsg: function () {
        let self = this;
        IsNewMsg = false;
        self.haveTodayDes = false;
        setTimeout(function () {
          jQuery("#unitSearchPopup").val("");
          self.clearContent();
          self.getList();
          getUnReadMsgCount();
        }, 100);
      },
      //全部标记为已读
      message_read: function () {
          // common.loading(1);
          Dao.operateMessage({
            ids: 'all',
            type: 2,
          }, function (data) { //设置全部已读  去除小红点
            // common.loading(0);
            // app.methods.showToastCenter("消息全部已读成功");
            
          }, function (e) {
            // common.loading(0);
            // app.methods.showToastBottom('消息全部已读失败');
          });

          // 参考市面常见app的做法，不做提示
          $(".msgbadge").hide();
          $("#redpoint_tab_msg").hide();
          // jQuery(".messge-toolTip").fadeOut(500).hide();
          $(".searchbar-found").css("padding-top", "0px");
          // jQuery("#contactslist").css("margin-top", "68px");
          // jQuery("#message_preloader").css("top", "35px");
      },
      //isRead 0未读 1已读 isSkip 0不需要跳转，1可以跳转
      getList: function () {
        let self = this;
        let pushTime = '';
        Dao.getMsgList({
            isMuilUnitUser:userInfor.isMuilUnitUser,
            orgIds: userInfor.organizationIds,
            selectContent: jQuery("#unitSearchPopup").val().trim(),
            pageIndex: self.pageIndex,
            pageSize: 25,
            orgCode: platformCode,
            userOrgCode: userInfor.org.orgCode,
            msgTypeIds: "", //类型筛选，暂无
        }, function (data) {
            if (data && data.length > 0) {
                //一直下拉直到没获取到数据
                if (data.length < 25) {
                    $("#msg-preloader").hide(); 
                    self.allowInfinite_mesage = false;
                } else {
                    $("#msg-preloader").show();
                    self.allowInfinite_mesage = true;
                }
                for (let i = 0; i < data.length; i++) {
                  if (data[i].pushTime) {
                      pushTime = moment(data[i].pushTime).format("YYYY-MM-DD HH:mm:ss");
                  }
                  let content = JSON.parse(data[i].content);
                  let pushType = data[i].pushType;

                  if (!self.haveTodayDes) {
                    //正好今日与昨日分页
                    if (!self.haveTodayDes && self.pushTimeIsToday && !common.judgeTimeIsToday(data[i].pushTime)) {
                        $("#contactslist").append(`<li class="link swipeout">
                            <div class="haveTodayDes">以上是今日消息</div>
                        </li>`);
                        self.haveTodayDes = true;
                    }
                  }

                  let pushTypeName = common.transNullundefined(data[i].pushTypeName);
                  if (2 === data[i].pushType) {
                      pushTypeName = "报警";
                  } else if (3 == data[i].pushType) {
                      pushTypeName = "故障";
                  } else if (4 == data[i].pushType) {
                      pushTypeName = "屏蔽";
                  } else if (5 == data[i].pushType) {
                      pushTypeName = "复位";
                  } else if (42 == data[i].pushType) {
                      pushTypeName = "联动";
                  }

                  $("#contactslist").append(
                    `<li class="link swipeout" id="messageList_` + data[i].id + `" >
                        <div class="swipeout-content">
                          <a href="#" class="item-link item-content" data-view=".view-main" style="padding-left:0;">
                              <div class="item-media">`+
                                    (
                                      data[i].isRead == 0?
                                      `<span id="readRedPoint_` + data[i].id + `" style="display: inline;" class="msgbadge badge color-red"></span>`:''
                                      )+
                              `<img style="" src="` + data[i].pushTypeIcon + `" width="40" />
                              </div>
                              <div class="item-inner">
                                <div class="item-title-row">
                                  <div class="item-title">` + pushTypeName + `</div>
                                  <div class="item-after time" style="opacity: 0.6;">` + pushTime + `</div>
                                </div>
                                <div style="color: #888888;font-size: 14px;line-height: 20px;">` + common.transNullundefined(data[i].title) + `</div>
                              </div>
                          </a>
                        </div>
                        <div class="swipeout-actions-right">
                            <a href="#" id="msgTransToReaded_` + data[i].id + `" style="display: none;" class="swipeout-close sign-read">标为已读</a>
                          </div>
                    </li>`);

                  //绑定点击事件,跳转
                  jQuery("#messageList_" + data[i].id).off().on('click', {'data': data[i]}, function (e) {
                      let res = e.data.data;
                        if(res.pushType=='9907'){
                          app.router.navigate(`/exam/`);
                        }else if(res.pushType=='1701'||res.pushType=='1702'){
                          app.router.navigate(`/closeReminder/`);
                        }else{
                          self.junpmThisPage(res);
                        }
                        let mes_id = this.id.split("_")[1];
                        self.quitRead(mes_id);
                        event.stopPropagation();
                  });

                  //绑定已读事件
                  if (data[i].isRead == 0) {
                      jQuery("#msgTransToReaded_" + data[i].id).show().off().click(function (event) {
                          let mes_id = this.id.split("_")[1];
                          self.quitRead(mes_id);
                          event.stopPropagation();
                      });
                  }

                  if (!self.haveTodayDes) {
                      if (common.judgeTimeIsToday(data[i].pushTime)) {
                          self.pushTimeIsToday = true;
                      }
                      if (common.judgeTimeIsToday(data[i].pushTime) && data[i + 1] && !common.judgeTimeIsToday(data[i + 1].pushTime)) {
                        $("#contactslist").append(`<li class="link swipeout">
                            <div class="haveTodayDes">以上是今日消息</div>
                        </li>`);
                        self.haveTodayDes = true;
                      }
                  }
                }
            } else {
                self.allowInfinite_mesage = false;
                $("#msg-preloader").hide();
                if (self.pageIndex == 0) {
                    $("#contactslist").empty().append(`<div class="no-data-img"><img src="` + listNoDataPic() +`"/></div>`);
                }
            }
            //无数据去除红点
            if ($("#contactslist").html().indexOf("defaultnone.png") > 0) {
                $("#redpoint_tab_msg").hide();
            }
        });
      },
      //标记已读
      quitRead: function (msgID) {
          let self = this;
          if($("#readRedPoint_" + msgID).length>0){
            Dao.operateMessage({
              ids: msgID,
              type: 2
            }, function (data) {
                $("#readRedPoint_" + msgID).remove();
                $("#msgTransToReaded_" +msgID).remove();
                // app.ptr.refresh();
                getUnReadMsgCount();
            });
          }
      },
      clearContent: function () {
          let self = this;
          self.pageIndex = 0;
          jQuery("#contactslist").empty();
      },
      //消息设置
      message_setup: function () {
          app.router.navigate("/messageSetin/");
      },
      //绑定点击事件
      junpmThisPage: function (res) {
        let self = this;
        let pushType = null;
        let context = null;
        if (res) {
          isFromMessage = 1;
          context = JSON.parse(res.content);
          pushType = res.pushType;
          //接处警
          if (jQuery.inArray(pushType, receivePoliceObj) > -1) {
            app.router.navigate("/policeHistoryDetail/" + context.fcFacilitiesId + "/" + context.businessId + "/" +
              context.createTime + "/");
          }
          //高危信号
          else if (jQuery.inArray(pushType, highRiskObj) > -1) {
            app.router.navigate("/fireHazardDetail/" + context.businessId + "/0/");
          }
          //重大问题
          else if (jQuery.inArray(pushType, majorIssuesObj) > -1) {
            app.router.navigate("/keyIssuesDetail/" + context.businessId + "/0/");
          }
          //查岗
          else if (jQuery.inArray(pushType, chagangObj) > -1) {
            isFromMessage = 0;
            //发起查岗类型
            if (pushType == 401) {
              Dao.getRecordsByInspectId_ajax({
                inspectId: context.businessId,
              }, function (data) {
                //多个用户应答
                if(data && data.inspectRecords.length > 0){
                    for(let i=0;i<data.inspectRecords.length;i++){
                        //当前用户
                        if(userInfor.accountName == data.inspectRecords[i].byCheckAccount){
                          if (data && data.inspectRecords[i].result == 1) {
                              push.pushDialog(res.pushTypeIcon, res.pushTypeName, res.title, ["立即应答", "取消"], function (dialog,index) {
                                //获取当前定位
                                native.requestLocation();
                                //延迟应答，接收原生经纬度数据
                                if (index != 1) {
                                  setTimeout(function () {
                                    Dao.responseTip({
                                      orgId: context.organizationId,
                                      inspectId: context.businessId,
                                      longitude: app.data.longitude,
                                      latitude: app.data.latitude
                                    }, function (data) {
                                      if (data.status == 200) {
                                        app.methods.showToastCenter("应答成功");
                                      } else {
                                        app.methods.showToastCenter(data.info);
                                      }
                                    });
                                  }, 1000);
                                }
                              });
                            } else if (data && data.inspectRecords[i].result == 2) {
                              app.methods.showToastCenter("任务超时");
                            } else {
                              app.methods.showToastCenter("已应答成功");
                            }
                            break;
                        }
                    }
                }
              });
            } else if (pushType == 402 || pushType == 403) {
              app.router.navigate("/inspectionApplyRecords/" + context.businessId + "/");
            }
          }
          //打卡
          else if (jQuery.inArray(pushType, clockObj) > -1) {
            app.router.navigate("/clockIn/");
          }
          //签到
          else if (jQuery.inArray(pushType, signObj) > -1) {
            app.router.navigate("/signInRecord/" + context.userAccount + "/");
          }
          //巡检
          else if (jQuery.inArray(pushType, inspectObj) > -1) {
            if (pushType == 701) { // 巡检开始
              app.router.navigate("/checkApply/0/0/0/0/");
            }else {
              // 完成、未完成、邀请
              app.router.navigate(`/checkApply/InspectDetail/${context.businessId}/${pushType==704?0:1}/0/`);
              // app.router.navigate("/inspectRecords/");
              // app.accordion.open("#checkApply_acc_" + context.businessId);
            }
          }
          //隐患整改
          else if (jQuery.inArray(pushType, hiddenDangersObj) > -1) {
            self.dealHiddenDanger(pushType, context);
          }
          //维保巡查
          else if (jQuery.inArray(pushType, maintenceInspectObj) > -1) {
            if (pushType == 901) {
              app.router.navigate("/maintainInspect/0/-1/");
            } else if (pushType == 902) {
              app.router.navigate("/maintainInspect/0/-1/");
            } else {
              app.router.navigate("/maintainInspectDetail/" + context.businessId + "/0/");
            }
          }
          //保养
          else if (jQuery.inArray(pushType, maintenceObj) > -1) {
            if (pushType == 1001 || pushType == 1002) {
              app.router.navigate("/maintain/0/-1/");
            } else {
              app.router.navigate("/maintainDetail/" + context.businessId + "/-1/");
            }
          }
          //单点测试
          else if (jQuery.inArray(pushType, singleTestObj) > -1) {
            if (pushType == 1101) {
              app.router.navigate("/singleTest/0/-1/");
            } else if (pushType == 1102) {
              app.router.navigate("/singleTest/1/-1/");
            } else {
              app.router.navigate("/singleTestDetail/" + context.businessId + "/0/");
            }
          }
          //联动测试
          else if (jQuery.inArray(pushType, linkTestObj) > -1) {
            if (pushType == 1201 || pushType == 1202) {
              app.router.navigate("/linkTest/0/-1/");
            } else if (pushType == 1203) {
              app.router.navigate("/linkTest/1/-1/");
            } else {
              app.router.navigate("/linkTestDetail/" + context.businessId + "/");
            }
          }
          //测试
          else if (jQuery.inArray(pushType, testObj) > -1) {
            if (context.maintainType == 1) {
              app.router.navigate("/maintainInspectDetail/" + context.businessId + "/0/");
            } else if (context.maintainType == 2) {
              app.router.navigate("/maintainDetail/" + context.businessId + "/0/");
            } else if (context.maintainType == 3) {
              app.router.navigate("/singleTestDetail/" + context.businessId + "/0/");
            } else if (context.maintainType == 4) {
              app.router.navigate("/linkTestDetail/" + context.businessId + "/");
            }
          }
          //临时任务
          else if (jQuery.inArray(pushType, temporaryTasksObj) > -1) {
            app.router.navigate("/temporaryTaskDetail/" + context.businessId + "/");
          }
          //作业申请
          else if (jQuery.inArray(pushType, applyForWorkObj) > -1) {
            app.router.navigate("/workApplyDetail/" + context.businessId + "/0/");
          }
          //应急救援
          else if (jQuery.inArray(pushType, emergencyObj) > -1) {
            self.dealYjjy(pushType, context);
          }
          //其它消息
          else if (jQuery.inArray(pushType, otherMsgObj) > -1) {
            //维保报告
            if (pushType == 9903) {
              app.router.navigate("/maintenceReport/" + context.businessId + "/"+context.orgName+"/月度/");
            }
            //消防报表
            else if (pushType == 9901) {
              app.router.navigate("/reportApplyDetail/" + context.businessId + "/" + context.isUnit + "/" + context.orgName + `/1/${context.period}/`);
            } else if (pushType == 9904) {
              app.router.navigate("/ninePlaceDetail/" +context.businessId + "/");
            }else if (pushType == 9908) {
              var year=context.year
              app.router.navigate("/reportApplyDetail/" +context.businessId + "/" + 3 + "/" + context.orgName + "/"+year+`/${context.period}/`);
            }
            else if (pushType == 9909) {
              var year=context.year
              app.router.navigate("/reportApplyDetail/" +context.businessId + "/" + 4 + "/" + context.orgName + "/"+year+`/${context.period}/`);
            }
          }
          //大屏视频通话
          else if (jQuery.inArray(pushType, bsVedioCall) > -1) {
            //APP在打开音视频对讲
            Dao.getAliRTCToken({
                channelID:context.channelID,	//Y	String	房间号
                user:userInfor.accountName	//Y	String	当前用户
            },function(result){
                if(result){
                  result.myName  = userInfor.name
                  result.channelID  = context.channelID
                  native.openBsVedioCall(result);
                }
            });
          }
        }
      },
      dealHiddenDanger: function (pushType, context) {
        let self = this;
        //获取这条隐患当前是什么状态
        Dao.getHidDanger({
          account: userInfor.accountName,
          hiddenDangerId: context.id,
        }, function (data) {
          if (data) {
            //1:整改中、2:已完成，3:核实中，5:待指派
            //待指派
            if (data.status == 5) {
              app.router.navigate("/goAppoint/" + context.businessId + "/");
            }
            //待整改
            else if (data.status == 1) {
              app.router.navigate("/goRectification/" + context.businessId + "/");
            }
            //待核实
            else if (data.status == 3) {
              app.router.navigate("/goVerify/" + context.businessId + "/");
            }
            //已完成
            else {
              app.router.navigate("/finishMsg/" + context.businessId + "/");
            }
          } else {
            app.methods.showToastCenter("未获取到隐患数据");
          }
        });
      },
      //应急救援
      dealYjjy: function (pushType, context) {
          let self = this;
          if (context) {
            if (context.status == 1) {
              app.router.navigate("/dealEmergencyApply/");
            } else {
              app.router.navigate('/emergencyDetail/' + context.planId + '/' + context.businessId + '/');
            }
          }
      },
      // 初始化事件
      initMessageFn(){
          let self = this;
          //enter事件
          jQuery("#unitSearchPopup").keypress(function (event) {
              if (event.which == 13) {
                  self.clearContent();
                  self.getList();
                  $("#unitSearchPopup").blur();
              };
          });
      },
      getMsgSetList: function () {
        var self = this;
        var $ = self.$$;
        Dao.getMsgPushStatusList({
            userName:userInfor.accountName,
            deviceId:appKeyObj.deviceId,
            orgCode: platformCode || app.data.defaultPlatCode,
        },function(data) {
          if(data.filter(n=>{ return n.status!=1 }).length>0){
            $('.page-message').addClass('show-msgSetNotice')
          }
          common.loading(0);
        },function(e) {
          common.loading(0);
        }, false);
      },
    },
    on: {
      pageInit: function (e, page) {
          let self = this;
          let $ = self.$;
          jQuery("#unitSearchPopup").val("");
          self.clearContent();
          self.initMessageFn();
          self.pushTimeIsToday = false;
          //显示统计未读消息数
          getUnReadMsgCount();
          self.getList();
          // 没有关闭消息设置通知
          if(!localStorage.getItem(`${userInfor.accountName}_closeMsgSetTip`)){
            self.getMsgSetList()
          }
      },
    }
  }
</script>

<style scoped>
  .link-tab-page-top .btn-clean-unread{
    display: none;
    position:absolute;
    top:15px;
    right:55px;
    align-items: center;
    height: 36px;
    font-size: 16px;
  }
  .btn-clean-unread .iconfont{
    margin-left: 3px;
    font-size: 26px;
  }
  #contactslist .item-after.time {
    font-size: 12px;
  }

  .md .list .item-after {
    font-family: Helvetica;
    font-size: 10px;
    color: #999999;
  }

  .haveTodayDes {
    font-family: HiraginoSansGB-W3;
    font-size: 14px;
    color: #cccccc;
    line-height: 40px;
  }

  .unitPopup-search {
    background-color: #1c3144 !important;
  }

  .messge-toolTip {
    height: 44px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(225, 225, 225, 0.9);
    box-shadow: 0px 1px 10px 0px rgba(181, 200, 206, 0.5);
    border-radius: 6px;
    margin: 0 20px;
    margin-top: 70px;
    padding: 0 10px;
    line-height: 42px;
    display: none;
  }

  .BJ_name {
    width: 100%;
    height: 46px;
    line-height: 46px;
    text-align: right;
    display: inline-block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    font-size: 14px;
    float: left;
  }

  .message-seartch {
    height: 30px !important;
    border-radius: 2px !important;
    width: auto !important;
    -webkit-box-shadow: 0 0 0px 0px rgba(0, 0, 0, .12), 0 0 0px rgba(0, 0, 0, .24) !important;
  }

  .inform {
    margin-top: 56px;
    width: 100%;
    height: 30px;
    background-color: #0772f4;
    font-size: 14px;
    text-align: center;
    color: #ffffff;
    position: fixed;
    opacity: 0.6;
    right: 0px;
    z-index: 1;
    line-height: 30px;
  }

  .unit-name {
    position: relative;
  }

  #contactslist .item-subtitle {
    font-size: 12px !important;
  }

  #contactslist li {
    width: 100%;
  }

  #contactslist .swipeout-content {
    width: 100%;
  }

  #contactslist .swipeout-content .item-media {
    padding-top: 18px;
  }

  .item-title {
    font-size: 17px;
    color: let(--black);
    font-family: HiraginoSansGB-W3;
  }

  .unit-select {
    position: absolute;
    left: 83px;
    top: 21px;
    width: 8px;
    height: 5px;
    background: url(../img/common/select-down.png);
    background-repeat: no-repeat;
  }

  .col {
    margin: 10px auto;
    font-size: 14px;
    text-align: center;
    color: #666666;
  }

  .f7-icons {
    font-size: 15px !important;
  }

  .MGleft {
    margin-left: 23%;
    position: relative;
  }

  .linenumber {
    color: #333333;
    font-size: 15px;
    padding-left: 10px;
    -webkit-line-clamp: 1;
    display: -webkit-box;
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
  }

  .message-type-img {
    width: 32px;
    height: 32px;
  }

  .cellWH {
    height: 70px;
    width: 100%;
  }

  .item-inner {
    position: relative;
  }

  #contactslist .item-title-row {
    padding-right: 0 !important;
    position: relative;
  }

  .message-title {
    font-size: 16px;
    color: #333333;
    float: left;
  }

  .message-time {
    font-size: 10px;
    color: #999999;
    float: left;
  }

  .message-contant {
    font-size: 12px;
    color: #888888;
    position: absolute;
    left: 15px;
    top: 38px;
    width: 60%
  }

  .circle {
    width: 8px;
    height: 8px;
    background: red;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    position: absolute;
    left: 53px;
    top: 20px;
  }

  .mytoas {
    background-color: #0772f4;
    font-size: 14px;
    color: white;
    text-align: center;
  }

  .msgbadge {
    padding: 0px;
    font-size: 1px;
    height: 6px;
    width: 6px;
    border-radius: 6px;
    position: absolute;
    top: 17px;
    left: 32px;
    display: none;
  }

  #contactslist:after {
    height: 0 !important;
  }

  .allRead {
    font-size: 12px;
    float: right;
    color: #2471CA;
  }

  #unreadMessages {
    display: inline;
    margin-left: 10px;
    position: absolute;
  }
</style>